const http = require('http');
const url = require('url');
const querystring = require('querystring');
const server = http.createServer((req, res) => {

    const { pathname } = url.parse(req.url, true);

    if (pathname === '/') {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('Hello World');
    } else if (pathname === '/login' && req.method === 'GET') {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(`
      <html>
        <head>
          <title>Login Page</title>
        </head>
        <body>
          <form method="POST" action="/login">
            <label for="username">Username:</label>
            <input type="text" id="username" name="username"><br><br>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password"><br><br>
            <input type="submit" value="Login">
          </form>
        </body>
      </html>
    `);
    } else if (pathname === '/login' && req.method === 'POST') {
        let body = '';
        req.on('data', chunk => {
            body += chunk.toString();
        });
        req.on('end', () => {
            console.log(body);
            const { username, password } = querystring.parse(body);
            console.log(`Username: ${username}, Password: ${password}`);
            if (username === 'admin' && password === 'password') {
                res.writeHead(302, { 'Location': '/' });
                res.end();
            } else {
                res.writeHead(401, { 'Content-Type': 'text/plain' });
                res.end('Invalid username or password');
            }
        });

    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Page not found');
    }
});


const port = 3000;

server.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/login`);
});

// This is a simple HTTP server that listens on port 3000 and returns "Hello World" as the response.    